/* function requireEntryTitle(req, res, next) {
    const title = req.body.entry.title;
    if (title) {
        next();
    } else {
        // res.error('Title is required.');
        next(new Error('Title is required.'))
        res.redirect('back');
    }
}

function requireEntryTitleLengthAbove(len) {
    return (req, res, next) => {
        const title = req.body.entry.title;
        if (title.length > len) {
            next();
        } else {
            // res.error(`Title must be longer than ${len}`);
            next(new Error(`Title must be longer than ${len}`));
            res.redirect('back');
        }
    }
}

exports.requireEntryTitle = requireEntryTitle;
exports.requireEntryTitleLengthAbove = requireEntryTitleLengthAbove; */

function parseField(field) {
    return field.split(/\[|\]/).filter((s) => s);
}

function getField(req, field) {
    let val = req.body;
    field.forEach(prop => {
        val = val[prop];
    });
    return val;
}

exports.required = (field) => {
    field = parseField(field);
    return (req, res, next) => {
        if (getField(req, field)) {
            next();
        } else {
            res.error(`${field.join(' ')} is required.`);
            // next(new Error(`${field.join(' ')} is required.`));
            res.redirect('back');
        }
    }
}

exports.lengthAbove = (field, len) => {
    field = parseField(field);
    return (req, res, next) => {
        if (getField(req, field).length > len) {
            next();
        } else {
            const fields = field.join(' ');
            res.error(`${fields} must have more than ${len} characters.`);
            // next(new Error(`${fields} must have more than ${len} characters.`));
            res.redirect('back');
        }
    }
}